package com.dmp.onlinestore.model.dao.testmemdb;

import java.util.List;
import java.util.ArrayList;
import com.dmp.onlinestore.model.dao.ProductDao;
import com.dmp.onlinestore.model.dao.base.*;
import com.dmp.onlinestore.model.dao.testmemdb.base.InMemDatabase;
import com.dmp.onlinestore.model.dto.ProductBean;
import com.dmp.onlinestore.model.dto.ProductBeanFilterSpec;
import com.dmp.onlinestore.system.Settings;

public class InMemProductDao implements ProductDao {
	
	public InMemProductDao(DaoTransaction transaction) {
		// No transaction support.
	}
	
	public List<ProductBean> getProducts(ProductBeanFilterSpec filter) throws DaoException {
		if (Settings.CONSOLE_DEBUG_ON) {
			System.out.println("InMemProductDao::getProducts");
		}
		List<ProductBean> matchingProdList = new ArrayList<ProductBean>();
	    for (ProductBean prod : InMemDatabase.instance().getProductList()) {
	    	// This would likely be done using a "where" clause
	    	// in SQL when talking to a real db.
	    	if (! filter.getCatMatch().equals(ProductBeanFilterSpec.STRING_MATCH_ANY)) {
	    		// We're matching on a specific category.
	    		if (! prod.getCategory().equals(filter.getCatMatch())) {
	    			// No match. Go to next product.
	    			continue;
	    		}
	    	}
	    	// This would likely be done using a "where" clause
	    	// in SQL when talking to a real db.
	    	if (! filter.getSubcatMatch().equals(ProductBeanFilterSpec.STRING_MATCH_ANY)) {
	    		// We're matching on a specific sub-category.
	    		if (! prod.getSubcategory().equals(filter.getSubcatMatch())) {
	    			// No match. Go to next product.
	    			continue;
	    		}
	    	}
	    	// We want this product, so store it. We clone the objects to 
	    	// insulate the in-memory database from application code.
	    	//ProductBean clonedProd = new ProductBean(prod);
	    	//prodList.add(clonedProd);
	    	matchingProdList.add(prod);
	    }
		return matchingProdList;
	}
	
	public ProductBean getProduct(int id) throws DaoException {
		if (Settings.CONSOLE_DEBUG_ON) {
			System.out.println("InMemProductDao::getProduct");
		}
		// This could be made more efficient with hashes or something...
		ProductBean match = null;
	    for (ProductBean prod : InMemDatabase.instance().getProductList()) {
	    	if (prod.getId() == id) {
	    		match = prod;
	    	}
	    }
    	return match;
	}
}